package org.huangrui.algorithm;

/**
 * @Author hr
 * @Create 2025-11-03 12:01
 * 二分查找
 * https://leetcode.cn/problems/binary-search/description/
 **/
public class T021LeetCode704 {
    /**
     * 输入: nums = [-1,0,3,5,9,12], target = 9
     * 输出: 4
     * 解释: 9 出现在 nums 中并且下标为 4
     *
     * @param nums
     * @param target
     * @return
     */
    public int search(int[] nums, int target) {
        // 一左一右两个指针相向而行
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int middle = (left + right) / 2;
            if (nums[middle] == target) {
                return middle; // 数组中找到目标值，直接返回下标
            } else if (nums[middle] < target) {
                left = middle + 1; // 结果比目标，小了要变大，左针右移+
            } else {
                right = middle - 1;// 结果比目标，大了要变小，右针左移-
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        T021LeetCode704 test = new T021LeetCode704();

        int[] nums = new int[]{-1, 0, 3, 5, 9, 12};
        // int target = 9;
        int target = 2;

        int ints = test.search(nums, target);
        System.out.println(ints);

    }
}
